package com.sinochem.sales.common.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.sinochem.sales.common.constant.CommonConstant;
import com.sinochem.sales.common.constant.KeyConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * 用户相关工具类
 *
 * @author xuan
 * @date 2017/11/20
 */
@Slf4j
public class UserUtils {
    private static final ThreadLocal<String> THREAD_LOCAL_USER = new TransmittableThreadLocal<>();
    private static final ThreadLocal<String> THREAD_LOCAL_UID = new TransmittableThreadLocal<>();

    /**
     * 根据请求heard中的token获取用户角色
     *
     * @param httpServletRequest request
     * @return 角色名
     */
    public static List<String> getRole(HttpServletRequest httpServletRequest) {
        String token = getToken(httpServletRequest);
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        List<String> roleNames = (List<String>) claims.get("authorities");
        return roleNames;
    }


    public static Map<String, Object> getUserIdByToken(String token) {
        String key = Base64.getEncoder().encodeToString(CommonConstant.SIGN_KEY.getBytes());
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    }

    /**
     * 获取请求中token
     *
     * @param httpServletRequest request
     * @return token
     */
    public static String getToken(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader(CommonConstant.REQ_HEADER);
        return StringUtils.substringAfter(authorization, CommonConstant.TOKEN_SPLIT);
    }

    /*获取用户名*/
    public static String getUser() {
        return THREAD_LOCAL_USER.get();
    }

    /*设置用户信息*/
    public static void setUser(String username) {
        THREAD_LOCAL_USER.set(username);
        MDC.put(KeyConstant.KEY_USER, username);
    }

    /*获取UID*/
    public static String getUID() {
        return THREAD_LOCAL_UID.get();
    }

    /*设置UID*/
    public static void setUID(String UID) {
        THREAD_LOCAL_UID.set(UID);
        MDC.put(KeyConstant.KEY_UID, UID);
    }

    public static void clearAllUserInfo() {
        THREAD_LOCAL_USER.remove();
        THREAD_LOCAL_UID.remove();
        MDC.remove(KeyConstant.KEY_USER);
        MDC.remove(KeyConstant.KEY_UID);
    }
}
